Java多线程 -- JUC包源码分析10 -- ConcurrentLinkedQueue源码分析

本人新书出版,对技术感兴趣的朋友请关注:
在这里插入图片描述

https://mp.weixin.qq.com/s/uq2cw2Lgf-s4nPHJ4WH4aw

在前面的篇章中,我们详细分析了AQS,并提到了里面一个关键数据结构:所有阻塞线程组成的一个等待队列,这个队列是用单向无锁链表实现的。

今天所讲的ConcurrentLinkedQueue,其实现和AQS中的无锁队列基本一样。所以,如果你深刻理解了AQS,ConcurrentLinkedQueue也就知道了。出于内容的完整性,在此还是列一下其源码:

public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
        implements Queue<E>, java.io.Serializable {

    //单向链表的Node
    private static class Node<E> {
        private volatile E item;
        private volatile Node<E> next;```
        。。。
    }

    //整个队列记录1头1尾2个结点
    private transient volatile Node<E> head = new Node<E>(null);
    private transient volatile Node<E> tail = head;

    //入队,也即cas tail (乐观锁)
    public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        Node<E> n = new Node<E>(e);
        retry:
        for (;;) {
            Node<E> t = tail;
            Node<E> p = t;
            for (int hops = 0; ; hops++) {
                Node<E> next = succ(p);
                if (next != null) {
                    if (hops > HOPS && t != tail)
                        continue retry;
                    p = next;
                } else if (p.casNext(null, n)) {
                    if (hops >= HOPS)
                        casTail(t, n); // Failure is OK.
                    return true;   
                } else {
                    p = succ(p);
                }
            }
        }
    }
    
    //出队,cas head,乐观锁
    public E poll() {
        Node<E> h = head;
        Node<E> p = h;
        for (int hops = 0; ; hops++) {
            E item = p.getItem();

            if (item != null && p.casItem(item, null)) {
                if (hops >= HOPS) {
                    Node<E> q = p.getNext();
                    updateHead(h, (q != null) ? q : p);
                }
                return item;
            }
            Node<E> next = succ(p);
            if (next == null) {
                updateHead(h, p);
                break;
            }
            p = next;
        }
        return null;
    }

   。。。
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值